const express = require('express');
const router = express.Router();
const User =require('../../models/User')
const Category=require('../../models/Category')
const Novel=require('../../models/Novel')
const Detail=require('../../models/Detail')
const WritingRecord = require('../../models/WritingRecord');
const jwt=require('jsonwebtoken')
const multer = require('multer');
const path = require('path');
const mongoose = require('mongoose');
const { v4: uuidv4 } = require('uuid');

// 计算字数的辅助函数
function calculateWordCount(content) {
  if (!content) return 0;
  // 优化：先去除HTML标签，再去除空格和换行，最后统计
  const text = content
    .replace(/<[^>]*>/g, '') // 去除HTML标签
    .replace(/\s+/g, '')     // 去除所有空格/换行
    .replace(/&nbsp;/g, ''); // 去除HTML空格实体
  // 仅统计中文字符（英文单词可根据需求保留）
  const chineseChars = (text.match(/[\u4e00-\u9fa5]/g) || []).length;
  // 若纯英文/数字，统计单词数（可选）
  const englishWords = text ? (text.trim().match(/\S+/g) || []).length : 0;
  return Math.max(chineseChars, englishWords); // 取较大值，避免均为0
}

const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1] // Bearer TOKEN

  if (!token) {
    return res.json({
      code: '2006',
      msg: '访问被拒绝，未提供token',
      data: null
    })
  }

  try {
    const verified = jwt.verify(token, 'my_secret')
    req.user = verified
    next()
  } catch (err) {
    return res.json({
      code: '2007',
      msg: '无效的token',
      data: null
    })
  }
}

router.get('/chapter/list', authenticateToken, async (req, res) => {
  try {
    const authorId = req.user.id;
    const { novelId, page = 1, pageSize = 999, status } = req.query;
    
    // 构建查询条件
    const queryCondition = { authorId };
    if (novelId && mongoose.Types.ObjectId.isValid(novelId)) {
      queryCondition.novelId = novelId;
    }
    if (status) {
      queryCondition.status = status;
    }
    
    // 分页参数
    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);
    
    // 查询章节列表（关联小说信息）
    const chapters = await Detail.find(queryCondition)
      .populate('novelId', 'title') // 关联小说标题
      .sort({ chapterNum: 1, pub_date: -1 }) // 按章节号正序，发布时间倒序
      .skip(skip)
      .limit(limit)
      .select('-__v');
    
    // 获取总数用于分页
    const total = await Detail.countDocuments(queryCondition);
    
    res.json({
      code: '0000',
      msg: '获取章节列表成功',
      data: {
        list: chapters.map(chapter => ({
          id: chapter._id,
          novelId: chapter.novelId?._id,
          novelTitle: chapter.novelId?.title,
          chapterNum: chapter.chapterNum,
          title: chapter.title,
          status: chapter.status, 
          pub_date: chapter.pub_date,
          content: chapter.content,
          // 在返回数据中添加
          word_count: chapter.word_count,
          read_time: chapter.read_time
        })),
        pagination: {//分页信息
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total
        }
      }
    });
  } catch (err) {
    res.json({ code: '2001', msg: '获取章节列表失败: ' + err.message, data: null });
  }
});

router.get('/chapter/detail', authenticateToken, async (req, res) => {
  try {
    const authorId = req.user.id;
    const { id } = req.query;
    
    if (!id) {
      return res.json({ code: '1001', msg: '章节ID不能为空', data: null });
    }
    
    const chapter = await Detail.findOne({ _id: id, authorId })
      .populate('novelId', 'title cate_name')
      .populate('authorId', 'username nickname')
      .select('-__v');
    
    if (!chapter) {
      return res.json({ code: '1002', msg: '章节不存在或无权访问', data: null });
    }
    
    res.json({
      code: '0000',
      msg: '获取章节详情成功',
      data: {
        id: chapter._id,
        novelId: chapter.novelId?._id,
        novelTitle: chapter.novelId?.title,
        novelCategory: chapter.novelId?.cate_name,
        chapterNum: chapter.chapterNum,
        title: chapter.title,
        status: chapter.status,
        pub_date: chapter.pub_date,
        content: chapter.content,
        // 在返回数据中添加
        word_count: chapter.word_count,
        read_time: chapter.read_time,
        author: {
          id: chapter.authorId?._id,
          name: chapter.authorId?.nickname || chapter.authorId?.username
        }
      }
    });
  } catch (err) {
    res.json({ code: '2002', msg: '获取章节详情失败: ' + err.message, data: null });
  }
});

router.post('/chapter/add', authenticateToken, async (req, res) => {
  try {
    const authorId = req.user.id;
    const { novelId, title, chapterNum, status = '草稿', content = '' } = req.body;
    // 计算字数
    const wordCount = calculateWordCount(content);
    const readTime = Math.ceil(wordCount / 300); // 假设300字/分钟
    
    // 参数验证
    if (!novelId || !title || chapterNum === undefined) {
      return res.json({ code: '1001', msg: '小说ID、标题和章节号不能为空', data: null });
    }
    
    // 验证小说是否存在且属于当前用户
    const novel = await Novel.findOne({ _id: novelId, userId: authorId });
    if (!novel) {
      return res.json({ code: '1002', msg: '小说不存在或无权操作', data: null });
    }
    
    // 检查章节号是否重复
    const existingChapter = await Detail.findOne({ novelId, chapterNum, authorId });
    if (existingChapter) {
      return res.json({ code: '1003', msg: '该章节号已存在', data: null });
    }
    
    // 创建新章节
    const newChapter = new Detail({
      novelId,
      authorId,
      title,
      chapterNum: parseInt(chapterNum),
      status,
      content,
      word_count: wordCount, // 新增
      read_time: readTime, // 新增
      pub_date: status === '发布' ? new Date() : null
    });

    const chapterData = {
      _id: newChapter._id,
      wordCount: wordCount, // 计算出的章节字数
      novelId: newChapter.novelId,
      title: newChapter.title,
      createdAt: newChapter.createdAt,
      updatedAt: newChapter.updatedAt
    };
    // 调用 WritingRecord 静态方法生成统计记录
    await WritingRecord.autoCreateRecord(authorId, chapterData);

    // 更新小说的字数统计和章节数
    await Novel.findByIdAndUpdate(novelId, {
      $inc: { 
        word_count: wordCount,
        chapter_count: 1 
      },
      last_update: new Date()
    });
    
    await newChapter.save();
    
    res.json({
      code: '0000',
      msg: '章节添加成功',
      data: {
        id: newChapter._id,
        title: newChapter.title,
        chapterNum: newChapter.chapterNum,
        status: newChapter.status,
        pub_date: newChapter.pub_date
      }
    });
  } catch (err) {
    res.json({ code: '2003', msg: '添加章节失败: ' + err.message, data: null });
  }
});

router.put('/chapter/edit', authenticateToken, async (req, res) => {
  try {
    const authorId = req.user.id;
    const { id, title, chapterNum, status, content } = req.body;
    
    if (!id) {
      return res.json({ code: '1001', msg: '章节ID不能为空', data: null });
    }
    
    // 1. 先查询原章节（用于计算字数差）
    const oldChapter = await Detail.findOne({ _id: id, authorId });
    if (!oldChapter) {
      return res.json({ code: '1002', msg: '章节不存在或无权编辑', data: null });
    }
    
    // 2. 构建更新数据
    const updateData = {};
    if (title !== undefined) updateData.title = title;
    if (chapterNum !== undefined) updateData.chapterNum = parseInt(chapterNum);
    if (status !== undefined) updateData.status = status;
    if (content !== undefined) updateData.content = content;
    if (status === '发布' && oldChapter.status !== '发布') {
      updateData.pub_date = new Date();
    }
    
    // 3. 若修改内容，重新计算字数并更新小说统计
    let updatedChapter;
    if (content !== undefined) {
      const wordCount = calculateWordCount(content);
      const readTime = Math.ceil(wordCount / 300);
      updateData.word_count = wordCount;
      updateData.read_time = readTime;
      
      // 4. 保存更新后的章节（关键：获取 updatedChapter）
      updatedChapter = await Detail.findByIdAndUpdate(id, updateData, { new: true });
      
      // 5. 计算字数差，更新小说统计
      const wordCountDiff = wordCount - oldChapter.word_count;
      await Novel.findByIdAndUpdate(oldChapter.novelId, {
        $inc: { word_count: wordCountDiff },
        last_update: new Date()
      });
      
      // 6. 生成 WritingRecord（使用更新后的章节数据）
      const chapterData = {
        _id: updatedChapter._id,
        wordCount: wordCount,
        novelId: updatedChapter.novelId,
        title: updatedChapter.title,
        createdAt: updatedChapter.createdAt,
        updatedAt: updatedChapter.updatedAt
      };
      await WritingRecord.autoCreateRecord(authorId, chapterData);
    } else {
      // 若未修改内容，直接保存更新
      updatedChapter = await Detail.findByIdAndUpdate(id, updateData, { new: true });
    }
    
    // 7. 正确返回更新后的章节数据
    res.json({
      code: '0000',
      msg: '章节编辑成功',
      data: {
        id: updatedChapter._id,
        title: updatedChapter.title,
        chapterNum: updatedChapter.chapterNum,
        status: updatedChapter.status,
        pub_date: updatedChapter.pub_date
      }
    });
  } catch (err) {
    res.json({ code: '2004', msg: '编辑章节失败: ' + err.message, data: null });
  }
});

router.delete('/chapter/delete', authenticateToken, async (req, res) => {
  try {
    const authorId = req.user.id;
    const { id } = req.body;
    
    if (!id) {
      return res.json({ code: '1001', msg: '章节ID不能为空', data: null });
    }
    
    // 1. 删除章节并获取删除的章节数据
    const deletedChapter = await Detail.findOneAndDelete({ _id: id, authorId });
    if (!deletedChapter) { // 正确判断章节是否存在
      return res.json({ code: '1002', msg: '章节不存在或无权删除', data: null });
    }
    
    // 2. 更新小说统计（减去删除章节的字数和章节数）
    await Novel.findByIdAndUpdate(deletedChapter.novelId, {
      $inc: { 
        word_count: -deletedChapter.word_count,
        chapter_count: -1 
      }
    });
    
    // 3. 删除关联的 WritingRecord（可选：根据业务需求决定是否删除历史记录）
    await WritingRecord.deleteMany({ chapterId: id, userId: authorId });
    
    res.json({
      code: '0000',
      msg: '章节删除成功',
      data: null
    });
  } catch (err) {
    res.json({ code: '2005', msg: '删除章节失败: ' + err.message, data: null });
  }
});



// 获取码字日历数据
router.get('/writing-calendar', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { year, month } = req.query; // 可选参数：指定年月
    
    // 构建查询条件
    const queryCondition = { userId };
    
    // 如果指定了年月，则查询该月份的数据
    if (year && month) {
      const startDate = new Date(year, month - 1, 1);
      const endDate = new Date(year, month, 0, 23, 59, 59);
      
      queryCondition.date = {
        $gte: startDate,
        $lte: endDate
      };
    } else {
      // 默认查询最近6个月的数据
      const sixMonthsAgo = new Date();
      sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
      queryCondition.date = { $gte: sixMonthsAgo };
    }
    
    // 查询写作记录，按日期分组统计
    const records = await WritingRecord.find(queryCondition)
      .populate('novelId', 'title')
      .sort({ date: 1 });
    
    // 按日期组织数据
    const calendarData = {};
    let totalWordCount = 0;
    let totalDays = 0;
    let currentStreak = 0;
    let longestStreak = 0;
    let tempStreak = 0;
    
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 初始化最近6个月的数据结构
    const sixMonthsAgo = new Date();
    sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
    sixMonthsAgo.setDate(1);
    
    // 生成日期范围
    const dateRange = [];
    let currentDate = new Date(sixMonthsAgo);
    while (currentDate <= today) {
      const dateKey = currentDate.toISOString().split('T')[0];
      calendarData[dateKey] = {
        date: new Date(currentDate),
        wordCount: 0,
        chapters: [],
        hasData: false
      };
      dateRange.push(dateKey);
      currentDate.setDate(currentDate.getDate() + 1);
    }
    
    // 填充实际数据
    records.forEach(record => {
      const dateKey = record.date.toISOString().split('T')[0];
      
      if (!calendarData[dateKey]) {
        calendarData[dateKey] = {
          date: record.date,
          wordCount: 0,
          chapters: [],
          hasData: false
        };
      }
      
      calendarData[dateKey].wordCount += record.wordCount;
      calendarData[dateKey].chapters.push({
        novelTitle: record.metadata?.novelTitle || '未知作品',
        chapterTitle: record.metadata?.chapterTitle || '未知章节',
        wordCount: record.wordCount,
        time: record.metadata?.publishTime || record.createdAt
      });
      calendarData[dateKey].hasData = true;
      
      totalWordCount += record.wordCount;
    });
    
    // 计算连续写作天数
    let currentDateForStreak = new Date(today);
    let foundBreak = false;
    
    while (!foundBreak && currentDateForStreak >= sixMonthsAgo) {
      const dateKey = currentDateForStreak.toISOString().split('T')[0];
      if (calendarData[dateKey]?.hasData) {
        currentStreak++;
        tempStreak++;
        longestStreak = Math.max(longestStreak, tempStreak);
      } else {
        if (currentDateForStreak.getTime() !== today.getTime()) {
          foundBreak = true;
        }
        tempStreak = 0;
      }
      currentDateForStreak.setDate(currentDateForStreak.getDate() - 1);
    }
    
    // 统计有写作的天数
    totalDays = Object.values(calendarData).filter(day => day.hasData).length;
    
    // 计算平均每日字数
    const avgDailyWords = totalDays > 0 ? Math.round(totalWordCount / totalDays) : 0;
    
    res.json({
      code: '0000',
      msg: '获取码字日历数据成功',
      data: {
        summary: {
          totalWordCount,
          totalDays,
          currentStreak,
          longestStreak,
          avgDailyWords
        },
        calendar: calendarData,
        dateRange: dateRange.sort() // 按日期排序
      }
    });
    
  } catch (err) {
    res.json({
      code: '2001',
      msg: '获取码字日历数据失败: ' + err.message,
      data: null
    });
  }
});

// 获取某天的详细写作记录
router.get('/writing-daily-detail', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { date } = req.query; // 格式: YYYY-MM-DD
    
    if (!date) {
      return res.json({
        code: '1001',
        msg: '日期参数不能为空',
        data: null
      });
    }
    
    const startDate = new Date(date);
    const endDate = new Date(date);
    endDate.setDate(endDate.getDate() + 1);
    
    const records = await WritingRecord.find({
      userId,
      date: {
        $gte: startDate,
        $lt: endDate
      }
    })
    .populate('novelId', 'title')
    .sort({ createdAt: -1 });
    
    const dailySummary = {
      date: startDate,
      totalWordCount: 0,
      chapters: [],
      writingTime: 0 // 总写作时间（分钟）
    };
    
    records.forEach(record => {
      dailySummary.totalWordCount += record.wordCount;
      dailySummary.writingTime += record.estimatedWritingTime || 0;
      
      dailySummary.chapters.push({
        id: record._id,
        novelId: record.novelId?._id,
        novelTitle: record.novelId?.title || record.metadata?.novelTitle || '未知作品',
        chapterTitle: record.metadata?.chapterTitle || '未知章节',
        wordCount: record.wordCount,
        writingTime: record.estimatedWritingTime || 0,
        publishTime: record.metadata?.publishTime || record.createdAt,
        source: record.source
      });
    });
    
    res.json({
      code: '0000',
      msg: '获取每日写作详情成功',
      data: dailySummary
    });
    
  } catch (err) {
    res.json({
      code: '2001',
      msg: '获取每日写作详情失败: ' + err.message,
      data: null
    });
  }
});

module.exports = router;